package com.yeyks.controller.common;

import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.em.ResponseStatus;
import com.yeyks.commonReference.append.app.OssService;
import com.yeyks.commonReference.service.account.AccountInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Api(tags = "文件上传模块")
@RestController
@RequestMapping("/ajax/file")
public class FileController {

    @Autowired
    private OssService ossService;

    @Autowired
    private AccountInfoService accountService;

    public Map<String, Object> ossUpload(Integer userId, MultipartFile file, Boolean rdName, Boolean pubArea) throws IOException {

        Map<String, Object> result = new HashMap<>();
        if (!file.isEmpty()) {

            String filename = file.getOriginalFilename();

            if (rdName != null && rdName) {
                int posDot = filename.lastIndexOf('.');
                if (posDot == -1) {
                    filename = UUID.randomUUID().toString();
                } else {
                    String ext = filename.substring(posDot);
                    filename = UUID.randomUUID().toString() + ext;
                }
            } else {
                int posDot = filename.lastIndexOf('.');
                if (posDot == -1) {
                    filename = UUID.randomUUID().toString();
                } else {
                    String ext = filename.substring(posDot);
                    filename = UUID.randomUUID().toString().replaceAll("-", "") + ext;
                }
            }

            String ossKey;
            if (pubArea != null && pubArea) {
                ossKey = "Public/" + filename;
            } else {
                ossKey = "User/" + userId.toString() + "/" + filename;
            }

            if (ossService.writeOSS(file.getBytes(), ossKey)) {
                result.put("filename", filename);
                result.put("absOssKey", ossKey);
                result.put("url", ossService.getPrefixUrl() + ossKey);
                result.put("status", ResponseStatus.RS_SUCCESS);
            } else {
                result.put("status", ResponseStatus.RS_FAIL_OSS_ENGINE);
            }
        } else {
            result.put("status", ResponseStatus.RS_FAIL_INVALID_PARAMETERS);
        }

        return result;
    }

    /**
     * 单文件的上传
     *
     * @param request
     * @param response
     * @param token
     * @param rdName
     * @param pubArea
     * @param file
     * @return
     */
    @ApiOperation(value = "4.2 --> 单文件的上传")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadFile(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(name = "token", defaultValue = "", required = true) String token,
            @RequestParam(name = "rdName", defaultValue = "", required = true) Boolean rdName,
            @RequestParam(name = "pubArea", defaultValue = "", required = true) Boolean pubArea,
            @RequestParam(name = "file") MultipartFile file
    ) {

        AjaxResponseBody responseBody = new AjaxResponseBody();
        try {
            Integer userId = accountService.token2UserId(token);
            Map rs = ossUpload(userId, file, rdName, pubArea);
            ResponseStatus responseStatus = ((ResponseStatus) rs.get("status"));

            responseBody.setBody(rs);
            responseBody.setCode(responseStatus.getCode());
            responseBody.setMsg(responseStatus.getMsg());
        } catch (Throwable e) {
            responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL.getMsg());
        }

        return ResponseEntity.ok(responseBody);
    }

//    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
//    public ResponseEntity<?> uploadFile(
//            HttpServletRequest request, HttpServletResponse response,
//            @RequestParam(name = "token", defaultValue = "", required = true) String token,
//            @RequestParam(name = "file") MultipartFile file
//    ) {
//
//        AjaxResponseBody responseBody = new AjaxResponseBody();
//        MultipartFile file1 = ((MultipartHttpServletRequest) request).getFile("file");
//        return ResponseEntity.ok(responseBody);
//    }

    /**
     * 多文件的上传
     *
     * @param request
     * @param response
     * @param token
     * @param rdName
     * @param pubArea
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public ResponseEntity<?> uploadFiles(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(name = "token", defaultValue = "", required = true) String token,
            @RequestParam(name = "rdName", defaultValue = "", required = true) Boolean rdName,
            @RequestParam(name = "pubArea", defaultValue = "", required = true) Boolean pubArea
    ) throws Exception {

        AjaxResponseBody responseBody = new AjaxResponseBody();
        List<String> resultList = new ArrayList<>();
        try {
            Integer userId = accountService.token2UserId(token);

            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
            List<Map> rsList = new ArrayList<>();
            if (files != null && !files.isEmpty()) {
                for (MultipartFile file : files) {
                    rsList.add(ossUpload(userId, file, rdName, pubArea));
                }

                responseBody.setBody(rsList);
                responseBody.setCode(ResponseStatus.RS_SUCCESS.getCode());
                responseBody.setMsg(ResponseStatus.RS_SUCCESS.getMsg());
            } else {
                responseBody.setCode(ResponseStatus.RS_FAIL_INVALID_PARAMETERS.getCode());
                responseBody.setMsg(ResponseStatus.RS_FAIL_INVALID_PARAMETERS.getMsg());
            }
        } catch (Throwable e) {
            responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL.getMsg());
        }

        return ResponseEntity.ok(responseBody);
    }

    /**
     * 上传酒店图片
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传模块 --> 上传酒店图片")
    @RequestMapping(value = "/upload/hotel/img", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadHotelImg(String hotelId, @RequestParam(name = "file") MultipartFile file) {
        Arguments.isTrue(null == file, "文件不能为空");
        String url = ossService.uploadHotelImg(hotelId, file);
        return ResponseEntity.ok(url);
    }

    /**
     * 上传房间图片
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传模块 --> 上传房间图片")
    @RequestMapping(value = "/upload/hotel/room/img", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadHotelImg(String hotelId, String roomId, @RequestParam(name = "file") MultipartFile file) {
        Arguments.isTrue(null == file, "文件不能为空");
        String url = ossService.uploadRoomImg(hotelId, roomId, file);
        return ResponseEntity.ok(url);
    }
}
